from rest_framework import serializers
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
import re

from celery_tasks.email.tasks import send_verify_email
from users.models import User, Address
from goods.models import SKU


class CreateUserSerializer(serializers.ModelSerializer):
    """创建用户序列化器"""
    #
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意用户协议', write_only=True)
    # 增加token字段,read_only：仅用于输出
    token = serializers.CharField(label='登录状态token', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'password2', 'mobile', 'sms_code', 'allow', 'token')

        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def validate_allow(self, value):
        """验证用户是否同意协议"""
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate(self, attrs):
        # 验证两次密码是否一致
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 验证短信验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile = attrs['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        # 判断短信验证码是否存在
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证码')

        # 比较用户输入的短信验证码与服务器端存储的短信验证码是否一致
        if real_sms_code.decode() != attrs['sms_code']:
            raise serializers.ValidationError('短信验证码错误')

        return attrs

    def create(self, validated_data):
        """创建用户"""
        # 先移除数据库模型类中不存在的属性
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        user = super().create(validated_data)

        # 调用django的认证系统加密密码
        user.set_password(validated_data['password'])
        user.save()

        # 生成JWToken
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 添加token到user对象中
        user.token = token

        return user


class UserCenterSerializer(serializers.ModelSerializer):
    """用户详情页序列化器"""
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'mobile', 'email_active']


class UpdateEmailSerializer(serializers.ModelSerializer):
    """增加邮箱序列化器"""
    class Meta:
        model = User
        fields = ['id', 'email']
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        """更改用户实例添加邮箱字段"""
        instance.email = validated_data.get('email')
        instance.save()

        # instance即User模型类的实例
        verify_url = instance.generate_verify_email_url()

        # 使用异步任务发送验证邮件
        send_verify_email.delay(instance.email, verify_url)

        return instance


class UserAddressSerializer(serializers.ModelSerializer):
    """用户地址序列化器"""
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """保存"""
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """地址标题"""
    class Meta:
        model = Address
        fields = ('title',)


class AddUserBrowseHistorySerialzier(serializers.Serializer):
    """用户浏览记录序列化器"""
    # 通过字段验证商品id是否为整型,且是否是以1开始
    sku_id = serializers.IntegerField(label='sku编号', min_value=1)

    def validate_sku_id(self, value):
        """验证商品sku是否存在"""
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value

    def create(self, validated_data):
        """保存用户浏览记录"""
        # 用户浏览记录需要用户的相关信息,所以需要从请求对象中获取
        user_id = self.context['request'].user.id
        sku_id = validated_data['sku_id']

        # 创建redis数据库对象进行存储工作
        redis_conn = get_redis_connection('history')

        # redis性能优化:使用管道进行集合式执行命令
        pl = redis_conn.pipeline()

        # 用户浏览记录逻辑一:去重
        pl.lrem('history_%s' % user_id, 0, sku_id)

        # 用户浏览记录逻辑二:添加数据,需根据浏览商品的时间,从左到右存
        pl.lpush('history_%s' % user_id, sku_id)

        # 用户浏览记录逻辑三:最多展示5条浏览记录,所以需要进行截取
        pl.ltrim('history_%s' % user_id, 0, 4)

        # 执行管道
        pl.execute()

        # 保存完毕后进行返回
        return validated_data
